package davion.study.summercloud.service;

import davion.study.summercloud.mapper.FileStoreMapper;
import davion.study.summercloud.mapper.UserMapper;
import davion.study.summercloud.model.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: Davion
 * @date: 2020/6/16
 * @description:
 */
@Service
public class UserService {

    @Resource
    UserMapper userMapper;

    @Resource
    FileStoreMapper fileStoreMapper;

    public User getByUuid(String uuid){
        UserExample example = new UserExample();
        example.createCriteria()
                .andUuidEqualTo(uuid);
        List<User> users = userMapper.selectByExample(example);
        return users.size() == 0 ? null : users.get(0);
    }

    public Boolean insert(User newUser) {
        return userMapper.insert(newUser) == 1;
    }

    public Boolean update(User dbUser) {
        return userMapper.updateByPrimaryKey(dbUser) == 1;
    }

    public User getById(int id) {
        return userMapper.selectByPrimaryKey(id);
    }

    public List<UserDTO> getAllUserInfoExceptSelf(Integer id) {
        UserExample userExample = new UserExample();
        userExample.createCriteria()
                .andIdNotEqualTo(id);
        List<User> dbUsers = userMapper.selectByExample(userExample);
        List<UserDTO> userDTOS = new ArrayList<>();
        for (User dbUser : dbUsers) {
            FileStoreExample storeExample = new FileStoreExample();
            storeExample.createCriteria()
                    .andUserIdEqualTo(dbUser.getId());
            FileStore fileStore = fileStoreMapper.selectByExample(storeExample).get(0);
            UserDTO userDTO = new UserDTO();
            userDTO.setId(dbUser.getId()).setName(dbUser.getUsername()).setLevel(dbUser.getLevel())
                    .setCreateTime(dbUser.getCreateTime()).setImage(dbUser.getImagePath())
                    .setMaxSize(fileStore.getMaxSize()).setCurrentSize(fileStore.getCurrentSize());
            userDTOS.add(userDTO);
        }
        return userDTOS;
    }

    public void updateUserLevel(Integer uId, Integer level, Integer size) {
        User dbUser = userMapper.selectByPrimaryKey(uId);
        dbUser.setLevel(level);
        userMapper.updateByPrimaryKey(dbUser);
        FileStoreExample storeExample = new FileStoreExample();
        storeExample.createCriteria()
                .andUserIdEqualTo(uId);
        FileStore fileStore = fileStoreMapper.selectByExample(storeExample).get(0);
        fileStore.setMaxSize(size * 1024);
        fileStoreMapper.updateByPrimaryKey(fileStore);
    }
}
